package com.wh.codedemon.datastructure;

class CycleSingleLinkList {

    private Node head;
    // 新增


    public CycleSingleLinkList() {
    }

    public void add(Node newNode) {
        if (head == null) {
            head = newNode;
            head.next = head;
            return;
        }
        Node currentNode = head;
        while (currentNode.next != head) {
            currentNode = currentNode.next;
        }
        currentNode.next = newNode;
        newNode.next = head;
    }

    public void delete(int no) {
        Node deleteNode = new Node(no);
        if (head == null) {
            return;
        }
        Node pre = head;
        Node tempNode = head;
        while (tempNode.next != head) {
            if (tempNode.no == deleteNode.no) {
                pre.next = tempNode.next;
                return;
            }
            pre = tempNode;
            tempNode = tempNode.next;
        }
    }

    public void show() {
        Node tempNode = head;
        while (tempNode.next != head) {
            System.out.println(tempNode);
            tempNode = tempNode.next;
        }
        // 输出剩余的
        System.out.println(tempNode);

    }

    /**
     * n个人围成一圈，从第一个开始报数，每次数到m的人出圈，然后下一个人重新开始报数，直到所有的人都出圈。
     */
    public void josephus(int m) {
        if (head == null || head.next == head) {
            System.out.println("空环");
            return;
        }
        Node pre = head, p;
        p = head;
        int flag = 1;
        while (p.next != p){
            if (flag == m){
                System.out.println("当前出圈的人:"+ p);
                pre.next = p.next;
                p = p.next;
                flag = 1;
            }else {
                pre = p;
                p = p.next;
                flag ++;
            }

        }
        System.out.println("最后剩余的人:" + p);


    }

    public static class Node {
        private int no;
        private Node next;

        public Node(int no) {
            this.no = no;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "no=" + no +
                    '}';
        }
    }


}
